package com.tbit.uqbike.client.business.captcha.service;

import com.anji.captcha.service.CaptchaCacheService;
import com.google.auto.service.AutoService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 验证码缓存实现，储存在redis以支持多实例
 *
 * @author <a href="mailto:zheng.zebiao@tbit.com.cn">zb</a>
 * @since 2024/12/11
 */
@AutoService(CaptchaCacheService.class)
public class CaptchaCacheServiceRedisImpl implements CaptchaCacheService {

    public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    private StringRedisTemplate stringRedisTemplate;


    @Override
    public void set(String key, String value, long expiresInSeconds) {
        stringRedisTemplate.opsForValue().set(key, value, expiresInSeconds, TimeUnit.SECONDS);
    }

    @Override
    public boolean exists(String key) {
        return stringRedisTemplate.hasKey(key);
    }

    @Override
    public void delete(String key) {
        stringRedisTemplate.delete(key);
    }

    @Override
    public String get(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }


    private static final String LUA_SCRIPT = "local key = KEYS[1] " +
            "local incrementValue = tonumber(ARGV[1]) " +
            "if redis.call('EXISTS', key) == 1 then " +
            "    return redis.call('INCRBY', key, incrementValue) " +
            "else " +
            "    return nil " +
            "end";

    @Override
    public Long increment(String key, long val) {
        DefaultRedisScript<Long> script = new DefaultRedisScript<>();
        script.setScriptText(LUA_SCRIPT);
        script.setResultType(Long.class);
        List<String> keys = Collections.singletonList(key);
        List<String> args = Collections.singletonList(String.valueOf(val));
        // 执行Lua脚本
        return stringRedisTemplate.execute(script, keys, args); // 如果键不存在，将返回null
    }

    @Override
    public String type() {
        return "redis";
    }
}
